﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;
using DataGrid导入导出.Base;
using PdfSharp.Drawing;
using PdfSharp.Fonts;
using PdfSharp.Pdf;
using Size = System.Windows.Size;

namespace DataGrid导入导出.Dialog
{
    /// <summary>
    /// PrintViewDialog.xaml 的交互逻辑
    /// </summary>
    public partial class PrintViewDialog : Window
    {
        public ICommand PrintCommand { get; set; }
        public ICommand CloseCommand { get; set; }
        public PrintQueueCollection PrinterList { get; set; }
        public PrintQueue CurrentPrinter { get; set; }
        public BitmapImage Image { get; set; }
        private FrameworkElement _element;

        public PrintViewDialog(FrameworkElement element)
        {
            InitializeComponent();

            PrintCommand = new BaseCommand(PrintElementToPdf);
            CloseCommand = new BaseCommand(DoClose);
            PrintServer printServer = new LocalPrintServer();
            PrinterList = printServer.GetPrintQueues();
            CurrentPrinter = PrinterList.Last();

            this.DataContext = this;
            this._element = element;

            InitPrintView();
        }

        private void InitPrintView()
        {
            DataGrid dataGrid = _element as DataGrid;

            // 先强制计算 DataGrid 的完整尺寸
            dataGrid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            dataGrid.Arrange(new Rect(new Size(dataGrid.DesiredSize.Width, dataGrid.DesiredSize.Height)));

            // 获取完整的宽度和高度
            double width = dataGrid.DesiredSize.Width;
            double height = dataGrid.DesiredSize.Height;

            RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
            renderTarget.Render(dataGrid);
            BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder();
            bmpEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
            MemoryStream mstream = new MemoryStream();
            bmpEncoder.Save(mstream);
            mstream.Position = 0;
            BitmapImage bmpImage = new BitmapImage();
            bmpImage.BeginInit();
            bmpImage.StreamSource = mstream;
            bmpImage.EndInit();
            Image = bmpImage;
        }

        public void PrintElementToPdf(object obj)
        {
            DataGrid dataGrid = _element as DataGrid;

            // 先强制计算 DataGrid 的完整尺寸
            dataGrid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            dataGrid.Arrange(new Rect(new Size(dataGrid.DesiredSize.Width, dataGrid.DesiredSize.Height)));

            // 获取完整的宽度和高度
            double width = dataGrid.DesiredSize.Width;
            double height = dataGrid.DesiredSize.Height;

            // 设置 PDF 页面大小（以 A4 纸为例）
            double pageWidth = 595;  // A4宽度（单位：点，1点=1/72英寸）
            double pageHeight = 842; // A4高度（单位：点）

            // 设置页边距（单位：点）
            double topMargin = 30;
            double bottomMargin = 20;
            double leftMargin = 10;
            double rightMargin = 10;

            // 创建 PDF 文档
            PdfDocument document = new PdfDocument();

            // 使用 RenderTargetBitmap 渲染元素
            RenderTargetBitmap rtb = new RenderTargetBitmap(
                (int)width,
                (int)height,
                96, 96, PixelFormats.Pbgra32);
            rtb.Render(dataGrid);

            // 计算实际的可用绘制区域（减去边距）
            double usableWidth = pageWidth - leftMargin - rightMargin;
            double usableHeight = pageHeight - topMargin - bottomMargin;

            // 计算需要多少页
            int rows = (int)(height / usableHeight) + 1; // 总页数的行数

            // 循环处理每一页
            for (int row = 0; row < rows; row++)
            {
                // 创建新页面
                PdfPage page = document.AddPage();
                XGraphics gfx = XGraphics.FromPdfPage(page);

                // 计算当前页的内容区域
                double xOffset = 0;
                double yOffset = row * usableHeight;

                // 限制偏移量，确保不超出内容的尺寸
                double cropHeight = Math.Min(usableHeight, height - yOffset);

                XFont font = new XFont("Arial", 14, XFontStyleEx.Bold);
                // 还是存在问题无法正确解析中文
                //GlobalFontSettings.FontResolver = new CustomFontResolver();
                //XFont font = new XFont("Microsoft YaHei UI", 15, XFontStyleEx.Bold);

                // 在每页顶部绘制标题
                string pageTitle = "我的 PDF 标题"; // 你可以根据需求动态设置标题

                gfx.DrawString(pageTitle, font, XBrushes.Black, new XPoint(leftMargin, topMargin - 10));
                gfx.DrawString($"Page {row + 1} of {rows}", font, XBrushes.Black, new XPoint(page.Width - 80, topMargin - 10));
                gfx.DrawLine(new XPen(XColors.Black, 2), 4, topMargin, page.Width - 8, topMargin);

                // 创建当前页的部分图像
                var croppedBitmap = CropBitmap(rtb, (int)xOffset, (int)yOffset, (int)pageWidth, (int)pageHeight);

                // 将裁剪的图像转换为 XImage
                using (var stream = new System.IO.MemoryStream())
                {
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(croppedBitmap));
                    encoder.Save(stream);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);
                    XImage xImage = XImage.FromStream(stream);

                    // 加上标题分割线的宽带 
                    double newTopMargin = topMargin + 4;
                    // 绘制图像到 PDF 页面
                    gfx.DrawImage(xImage, leftMargin, newTopMargin, usableWidth, usableHeight);
                }
            }

            // 保存 PDF 文档
            document.Save("222.pdf");
        }

        private void DoPrint(object obj)
        {
            DataGrid dataGrid = _element as DataGrid;

            // 先强制计算 DataGrid 的完整尺寸
            dataGrid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            dataGrid.Arrange(new Rect(new Size(dataGrid.DesiredSize.Width, dataGrid.DesiredSize.Height)));

            // 获取完整的宽度和高度
            double width = dataGrid.DesiredSize.Width;
            double height = dataGrid.DesiredSize.Height;

            RenderTargetBitmap rtb = new RenderTargetBitmap(
                (int)width,
                (int)height,
                96, 96, PixelFormats.Pbgra32);

            rtb.Render(dataGrid);

            PdfDocument document = new PdfDocument();

            using (var stream = new System.IO.MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                encoder.Save(stream);

                stream.Seek(0, System.IO.SeekOrigin.Begin);
                XImage xImage = XImage.FromStream(stream);

                int pageCount = (int)Math.Ceiling(height / 842);
                for (int i = 0; i < pageCount; i++)
                {
                    PdfPage page = document.AddPage();
                    XGraphics gfx = XGraphics.FromPdfPage(page);
                    gfx.DrawImage(xImage, 0, i * page.Height, page.Width, page.Height);
                }
            }

            document.Save("111.pdf");

            Task.Run(() =>
            {
                PrintDialog printDialog = new PrintDialog();
                printDialog.PrintTicket.PageBorderless = PageBorderless.Borderless;
                printDialog.PrintTicket.PageOrientation = PageOrientation.Portrait;
                printDialog.PrintTicket.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4);
                printDialog.PrintQueue = CurrentPrinter;

                this.Dispatcher.Invoke(() =>
                {
                    printDialog.PrintVisual(dataGrid, "打印");
                });
            });
            MessageBox.Show("正在打印...");
        }

        // 辅助方法：裁剪 RenderTargetBitmap
        private RenderTargetBitmap CropBitmap(RenderTargetBitmap sourceBitmap, int x, int y, int width, int height)
        {
            // 创建一个新的 RenderTargetBitmap 来保存裁剪后的图像
            RenderTargetBitmap croppedBitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);

            // 将源图像的部分内容绘制到新的图像上
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                drawingContext.DrawImage(sourceBitmap, new Rect(-x, -y, sourceBitmap.PixelWidth, sourceBitmap.PixelHeight));
            }

            // 渲染裁剪后的内容
            croppedBitmap.Render(drawingVisual);
            return croppedBitmap;
        }

        private void DoClose(object obj)
        {
            this.DialogResult = true;
        }
    }
}
